<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 列表区 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRolesDialog = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区 -->
      <el-table :data="RolesList" border>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdBottom', i1 === 0 ? 'bdTop':'','vcenter']" v-for="(item1, i1) in scope.row.children"
                    :key="item1.id">
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级三级权限 -->
              <el-col :span="19">
                <el-row :class="[i2 === 0 ? '':'bdTop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" v-for="(item3) in item2.children" :key="item3.id" closable
                            @close="removeRightById(scope.row,item3.id)">{{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="getEditRoles(scope.row.id)">修改</el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeRoleById(scope.row.id)">删除
            </el-button>
            <el-button type="warning" size="mini" icon="el-icon-sitting" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加弹框 -->
    <el-dialog title="添加角色" :visible.sync="addRolesDialog" width="50%" @close="addRolesClose">
      <el-form :model="addRole" :rules="roleRoles" label-width="100px" ref="addRolesRef">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRole.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input type="textarea" v-model="addRole.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialog = false">取 消</el-button>
        <el-button type="primary" @click="addRolesInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改弹框 -->
    <el-dialog title="修改角色" :visible.sync="editRolesDialog" width="50%" @close="editRolesClose">
      <el-form :model="editRoles" label-width="100px" ref="editRolesRef">
        <el-form-item label="角色名称">
          <el-input v-model="editRoles.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input type="textarea" v-model="editRoles.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesDialog = false">取 消</el-button>
        <el-button type="primary" @click="editRolesInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 权限弹框 -->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="setRightsClose">
      <!-- 树型控件 -->
      <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id" default-expand-all
               :default-checked-keys="defaultRights" ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
    <el-button @click="setRightDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allowRights">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data () {
    return {
      /* 校验 */
      roleRoles: {
        roleName: [
          {
            required: true,
            message: '角色名不能为空！',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 8,
            message: '角色名的长度为2至8位',
            trigger: 'blur'
          }
        ],
        roleDesc: [
          {
            min: 1,
            max: 100,
            message: '描述的长度为1至100位',
            trigger: 'blur'
          }
        ]
      },
      /* 所有角色列表数据 */
      RolesList: [],
      /* 添加弹框 显示与隐藏 */
      addRolesDialog: false,
      /* 添加角色 */
      addRole: {
        roleName: '',
        roleDesc: ''
      },
      /* 修改弹框 显示与隐藏 */
      editRolesDialog: false,
      /* 根据id查询的数据 */
      editRoles: {},
      /* 分配权限对话框 */
      setRightDialogVisible: false,
      /* 所有权限列表 */
      rightsList: [],
      /* 树型控件的属性绑定 */
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      /* 默认权限 */
      defaultRights: [],
      /* 即将分配权限的角色id */
      roleId: ''
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    /* 获取所有角色列表数据 */
    async getRolesList () {
      const { data: res } = await this.$http.get('/roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      this.RolesList = res.data
    },
    /* 监听添加弹框对话事件 还原操作 */
    addRolesClose () {
      this.$refs.addRolesRef.resetFields()
    },
    /* 提交添加信息 */
    addRolesInfo () {
      this.$refs.addRolesRef.validate(async valid => {
        if (!valid) return false
        /* 预校验通过 */
        const { data: res } = await this.$http.post('/roles', this.addRole)
        if (res.meta.status !== 201) {
          return this.$message.error('角色添加失败!')
        }
        this.addRolesDialog = false
        this.getRolesList()
        this.$message.success('角色添加成功！')
      })
    },
    /* 根据id查询 */
    async getEditRoles (id) {
      const { data: res } = await this.$http.get('/roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败！')
      }
      this.editRoles = res.data
      this.editRolesDialog = true
    },
    /* 监听修改弹框对话事件 还原操作 */
    editRolesClose () {
      this.$refs.editRolesRef.resetFields()
    },
    /* 提交修改信息 */
    async editRolesInfo () {
      const { data: res } = await this.$http.put('/roles/' + this.editRoles.roleId, {
        roleName: this.editRoles.roleName,
        roleDesc: this.editRoles.roleDesc
      })
      if (res.meta.status !== 200) {
        return this.$message.error('修改失败！')
      }
      this.editRolesDialog = false
      this.getRolesList()
      return this.$message.success('修改成功！')
    },
    /* 删除 */
    async removeRoleById (id) {
      const removeResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => {
        return error
      })
      /* 取消按钮 返回值 cancel 确认按钮 返回值 confirm */
      if (removeResult !== 'confirm') {
        return this.$message.info('已取消删除！')
      }
      /* 删除 */
      const { data: res } = await this.$http.delete('/roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除失败！')
      this.getRolesList()
      this.$message.success('删除成功！')
    },
    /* 删除权限 */
    async removeRightById (role, id) {
      const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除操作！')
      }
      const { data: res } = await this.$http.delete(`/roles/${role.id}/rights/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除操作失败！')
      }
      role.children = res.data
      this.$message.success('删除操作成功！')
    },
    /* 获取权限 */
    async showSetRightDialog (role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('权限列表获取失败！')
      }
      this.rightsList = res.data
      this.getLeafkeys(role, this.defaultRights)
      this.setRightDialogVisible = true
    },
    /* 通过递归的形式 获取角色下 所有三级权限id */
    getLeafkeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafkeys(item, arr)
      })
    },
    /* 监听分配权限对话框关闭事件 */
    setRightsClose () {
      this.defaultRights = []
    },
    /* 点击分配权限 */
    async allowRights () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const isKeys = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: isKeys })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败！')
      }
      this.setRightDialogVisible = false
      this.getRolesList()
      return this.$message.success('分配权限成功！')
    }
  }
}
</script>

<style lang="less" scoped>
  .el-tag {
    margin: 7px;
  }

  .bdTop {
    border-top: 1px solid #eee;
  }

  .bdBottom {
    border-bottom: 1px solid #eee;
  }

  .vcenter {
    display: flex;
    align-items: center;
  }
</style>
